package cn.maidouya.basic.util;

import cn.maidouya.user.domain.Logininfo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.http.HttpServletRequest;

/**
 *   登录上下文  非Spring容器管理
 *   登录相相关信息
 *          当前登录人信息
 *          当前登录人所拥有的权限和角色
 *   获取Spring容器管理的Bean属性
 */
public class LoginContext {
    public static Logininfo getLogininfo(HttpServletRequest request){
        // 1. 获取容器对象
        WebApplicationContext application = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
        // 2. 从容器中获取Bean属性
        RedisTemplate redisTemplate = application.getBean("redisTemplate", RedisTemplate.class);

        // 3. 获取登录人token
        String token = request.getHeader("token");
        // 4. 获取登录人缓存信息
        Object logininfoObj = redisTemplate.opsForValue().get(token);
            if (logininfoObj != null){
                Logininfo logininfo = (Logininfo)logininfoObj;
                return logininfo;
            }
        return null;
    }
}